package com.lonely.fx;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * @date: 2022-07-27 10:24
 * @author: ztkj-hzb
 * @description:
 **/
public class 将图片转成字符画 extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    /**
     *
     */
    @Override
    public void start(Stage primaryStage) throws Exception {


        VBox vBox = new VBox();
        vBox.setSpacing(30);

        HBox hBox = new HBox();
        hBox.setSpacing(30);
        hBox.setPadding(new Insets(50));
        hBox.setAlignment(Pos.CENTER);
        hBox.setFillHeight(true);

        Label label = new Label("请选择原图片：");

        TextField textField = new TextField();
        textField.setPromptText("图片地址");
        textField.setPrefWidth(400);
        textField.setEditable(false);

        Button button = new Button("选择文件");
        Button button2 = new Button("转换文件");


        HBox hBox2 = new HBox();
        ImageView imageView = new ImageView();

        button.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                //打开选择文件框

                FileChooser fileChooser = new FileChooser();
                fileChooser.setInitialDirectory(new File("C:\\Users\\汪娇\\Pictures"));
                File file = fileChooser.showOpenDialog(primaryStage);
                if (file == null) {
                    return;
                }

                //将图片路径回写在文本框中
                String absolutePath = file.getAbsolutePath();
                textField.setText(absolutePath);

                //图片框中加载图片
                Image image = null;
                try {
                    image = new Image(new FileInputStream(file));

                    int newWidth =0;
                    int newHeight = 0;
                    if(image.getWidth() > 300){
                        newWidth = 300;
                    }


                    //等比例缩放10倍
                    //int newWidth = (int) image.getWidth() / 50;
                    //int newHeight = (int) image.getHeight() / 50;

                    image = new Image(new FileInputStream(file),newWidth,newHeight,true,true);
                    //imageView.setPreserveRatio(true);
                    //imageView.setFitWidth(500);

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                imageView.setImage(image);

                /*if (image.getWidth() > 500) {
                    imageView.setPreserveRatio(true);
                    imageView.setFitWidth(500);
                }*/

            }
        });


        button2.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                if (imageView.getImage() == null) {
                    return;
                }


                Image image = imageView.getImage();

                System.out.println(image.getWidth());
                System.out.println(image.getHeight());

                /*if(true){
                    return;
                }*/

                String convertImage = convertImage(image);

                //保存到本地
                try {
                    FileOutputStream fileOutputStream = new FileOutputStream(new File("D:/a.txt"));
                    fileOutputStream.write(convertImage.getBytes(StandardCharsets.UTF_8));
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });

        hBox.getChildren().addAll(label, textField, button, button2);
        hBox2.getChildren().addAll(imageView);
        vBox.getChildren().addAll(hBox, hBox2);
        primaryStage.setScene(new Scene(vBox));
        primaryStage.setWidth(900);
        primaryStage.setHeight(600);
        primaryStage.show();


    }


    /**
     * 将图片转换成字符画
     *
     * @param image
     * @return
     */
    private String convertImage(Image image) {

        PixelReader pixelReader = image.getPixelReader();

        //读取像素数据
        int[] intBuff = new int[(int) image.getWidth() * (int) image.getHeight()];
        pixelReader.getPixels(0, 0, (int) image.getWidth(), (int) image.getHeight(),
                PixelFormat.getIntArgbPreInstance(), intBuff, 0, (int) image.getWidth());

        StringBuilder result = new StringBuilder();
        //解析数据
        for (int i = 0; i < intBuff.length; i++) {
            //解析出红色
            int red = intBuff[i] >> 16 & 0xff;
            result.append(pixedToString(red));

            if (i > 0 && i % image.getWidth() == 0) {
                //换行
                result.append("\r\n");
            }
        }

        return result.toString();
    }


    /**
     * 像素红 转成 字符
     * 颜色越暗，值越小
     *
     * @param pixed
     * @return
     */
    private String pixedToString(int pixed) {

        int qj = pixed / 10;

        if (qj >= 0 && qj <= 5) {
            return "#";
        }

        if (qj >= 5 && qj <= 10) {
            return "W";
        }

        if (qj > 10 && qj <= 15) {
            return "%";
        }
        if (qj > 15 && qj <= 20) {
            return "s";
        }

        return " ";
    }
}
